#pragma once

#include <qgraphicsscene.h>
#include "LayoutObject.h"
#include <QMap>
#include "objectvisual.h"
#include <QGraphicsView>
#include <QMouseEvent>
#include <QObject>
class LayoutView : public QGraphicsView
{
	Q_OBJECT
public:
	LayoutView(QWidget* owner = nullptr);
	~LayoutView(void);
public:
	void drawGrid(const QRect rect);
public slots:
	void OnSelectionChanged(ObjectVisual* caller);
signals:
	void SelectionChanged();
public:
	QList<QGraphicsItem*> LayoutView::getSelectedItem();
	void SyncNewObject(LayoutObject* newModelObject)
	{		
		auto ov = new ObjectVisual(newModelObject);
		visualsMap_[newModelObject] = ov;
		scene_.addItem(ov);
		ov->setPos(newModelObject->Position());
		ov->setRotation(newModelObject->Orientation());
		
		connect((QObject*)ov, SIGNAL(SelectionChanged(ObjectVisual*)), 
			SLOT(OnSelectionChanged(ObjectVisual*)));

		//ov->rotate(newModelObject->Orientation());
	}
	void DesyncObject(LayoutObject* oldObj)
	{
		auto visual = visualsMap_[oldObj];
		visualsMap_.remove(oldObj);
		disconnect((QObject*)visual);
		scene_.removeItem(visual);
		delete visual;	
	}
	void Reset()
	{
		for(auto it = visualsMap_.begin(); it != visualsMap_.end();
			it++)
		{
			auto v = it.value();
			scene_.removeItem(v);
			delete v;
		}
		visualsMap_.clear();
	}
	
	void mouseMoveEvent(QMouseEvent * event);
	void mousePressEvent(QMouseEvent * event);
	void mouseReleaseEvent(QMouseEvent * event);

private:
	QGraphicsScene scene_;
	QMap<LayoutObject*, ObjectVisual*> visualsMap_;
	QPointF previousMousePosition_;
};

